package com.jy.wms.common.generator;

import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class GenEntityMysql {  
	private final String type_char = "char";
 
    private final String type_date = "date";
 
    private final String type_timestamp = "timestamp";
 
    private final String type_int = "int";
 
    private final String type_bigint = "bigint";
 
    private final String type_text = "text";
 
    private final String type_bit = "bit";
 
    private final String type_decimal = "decimal";
 
    private final String type_blob = "blob";
    protected String pojobasepath="wms.src.main.java";
    protected String mapperbasepath="wms.src.main.java";
    protected String mapperxmlbasepath="wms.src.main.resources";

    protected String servicebasepath="wms.src.main.java";
    protected String controllerBasePath="wms.src.main.java";

    protected String packageOutPath = "com.jy.wms.pojo";//指定实体生成所在包的路径
    protected String packageOutDao = "com.jy.wms.dao";//在外边配置一下
    protected String packageOutMapper = "mapper";//在外边配置一下
    protected String packageOutServiceImpl = "com.jy.wms.service";//serivceimpl
    protected String packageOutController = "com.jy.wms.controller";//serivceimpl

    protected String authorName = "zzp";//作者名字
    protected static String tablename = "jy_user";//表名
    protected static String javaMapperDao = "UserDao";//表名  在外边配置一下
    protected static String javaMapper = "UserMapper";//表名  在外边配置一下
    protected List<String> colnames; // 列名数组
    protected List<String> colTypes; //列名类型数组
    protected List<String> bzstr;//备注
    protected int[] colSizes; //列名大小数组
    private boolean f_util = false; // 是否需要导入包java.util.*  
    private boolean f_sql = false; // 是否需要导入包java.sql.*  
    private static String javaFileName="";
    //数据库连接  
    private static String URL ="jdbc:mysql://localhost:3306/wms";
    private static String NAME = "root";
    private static String PASS = "root";  
    private static String DRIVER ="com.mysql.jdbc.Driver";  
    private String daoMapper="dao";
    protected String tableKey="";
    /*
     * 构造函数 
     */  
    public GenEntityMysql(){
      	Properties prop =  new  Properties();
      	InputStream ins =Object.class.getResourceAsStream("/createBean.properties");
    	try {
			prop.load(ins);
		} catch (IOException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		URL=prop.getProperty("URL");
	  	PASS=prop.getProperty("PASS");
	  	DRIVER=prop.getProperty("DRIVER");
	  	NAME=prop.getProperty("NAME");
	  	tablename=prop.getProperty("tablename");
	  	javaFileName=prop.getProperty("javaFileName");
	  	javaMapperDao=prop.getProperty("javaMapperDao");
	  	javaMapper=prop.getProperty("javaMapper");
        authorName=prop.getProperty("authorName");
        //创建连接  
        Connection con = null;  
        //查要生成实体类的表  
        String sql = "show full fields from "+ tablename;

        //String sql = "select * from " + tablename;
        PreparedStatement pStemt = null;  
        try {  
            try {  
                Class.forName(DRIVER); 
            } catch (ClassNotFoundException e1) {
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
            }  
            con = DriverManager.getConnection(URL,NAME,PASS);  
          
            pStemt = con.prepareStatement(sql);  
            ResultSet rs=pStemt.executeQuery();

            colnames = new ArrayList<String>();
            bzstr = new ArrayList<String>(); 
            colTypes = new ArrayList<String>();
           while (rs.next()) {
                if("PRI".equals(rs.getString("KEY"))){
                    tableKey=rs.getString("FIELD");
                }
				colnames.add(rs.getString("FIELD"));
				colTypes.add(rs.getString("TYPE"));
			    bzstr.add(rs.getString("COMMENT"));
            }
            System.out.println(tableKey);
             /**
              * 构建生成实体bean
              */
            String content = parse(colnames,colTypes,colSizes,bzstr,tablename);

            try {  
                File directory = new File("");  
                String path=this.getClass().getResource("").getPath();
                String outputPath = directory.getAbsolutePath()+ "/"+this.pojobasepath.replace(".", "/")+"/"+this.packageOutPath.replace(".", "/")+"/"+initcap(javaFileName) + ".java";

              writeFile(outputPath,content);//创建bean

            } catch (Exception e) {
                e.printStackTrace();  
            }
              
        } catch (SQLException e) {  
            e.printStackTrace();  
        } finally{  
          try {  
             con.close();  
         } catch (SQLException e) {  
             // TODO Auto-generated catch block  
            e.printStackTrace();  
         }  
        }  
    }

	/** 
     * 功能：生成实体类主体代码
     * @autor zzp
     * @param colnames 列名
     * @param colTypes 列类型
     * @param colSizes 列长度
     * @param bzstr 描述
     * @return 
     */  
    private String parse(List<String> colnames,List<String> colTypes, int[] colSizes, List<String> bzstr,String tablename) {
        StringBuffer sb = new StringBuffer();  
          
        //判断是否导入工具包  
       /* if(f_util){  
            sb.append("import java.util.Date;\r\n");  
        }  
        if(f_sql){  
            sb.append("import java.sql.*;\r\n");  
        }  */
        sb.append("package " + this.packageOutPath + ";\r\n");
        sb.append("\r\n");
        sb.append("import com.baomidou.mybatisplus.annotations.TableName;\r\n");
        sb.append("import com.jy.wms.common.base.BaseModel;\r\n");
        sb.append("import java.io.Serializable;\r\n");
        //注释部分  
        sb.append("   /**\r\n");  
        sb.append("    * "+javaFileName+" 实体类\r\n");  
        sb.append("    * "+new Date()+" "+this.authorName+"\r\n");  
        sb.append("    */ \r\n"); 
        sb.append("\r\n@SuppressWarnings(\"serial\")");
        sb.append("\r\n@TableName(\""+tablename+"\")");
        //实体部分  
        sb.append("\r\npublic class " + initcap(javaFileName) + " extends BaseModel implements Serializable {\r\n");
        processAllAttrs(sb);//属性  
        processAllMethod(sb);//get set方法  
        sb.append("}\r\n");
        return sb.toString();  
    }  
      
    /** 
     * 功能：生成所有属性 
     * @param sb 
     */  
    private void processAllAttrs(StringBuffer sb) {
    	int size=colnames.size();
        for (int i = 0; i < size; i++) {  
            sb.append("\tprivate " + processType(colTypes.get(i)) + " " + colnames.get(i) + "; \t//" + bzstr.get(i) + "\r\n");  
        }  
          
    }  
  
    /** 
     * 功能：生成所有方法 
     * @param sb 
     */  
    private void processAllMethod(StringBuffer sb) {  
    	int size=colnames.size();
        for (int i = 0; i < size; i++) {  
            sb.append("\tpublic void set" + initcap(colnames.get(i)) + "(" + processType(colTypes.get(i)) + " " +   
            		colnames.get(i) + "){\r\n");  
            sb.append("\t\tthis." + colnames.get(i) + "=" + colnames.get(i) + ";\r\n");  
            sb.append("\t}\r\n");  
            sb.append("\tpublic " + processType(colTypes.get(i)) + " get" + initcap(colnames.get(i)) + "(){\r\n");  
            sb.append("\t\treturn " + colnames.get(i) + ";\r\n");  
            sb.append("\t}\r\n");  
        }

    }
      
    /** 
     * 功能：将输入字符串的首字母改成大写 
     * @param str 
     * @return 
     */  
    private String initcap(String str) {  
          
        char[] ch = str.toCharArray();  
        if(ch[0] >= 'a' && ch[0] <= 'z'){  
            ch[0] = (char)(ch[0] - 32);  
        }  
          
        return new String(ch);  
    }  
  
    /** 
     * 功能：获得列的数据类型 
     * @param sqlType 
     * @return 
     */  
    private String sqlType2JavaType(String sqlType) {  
          
        if(sqlType.equalsIgnoreCase("bit")){  
            return "boolean";  
        }else if(sqlType.equalsIgnoreCase("tinyint")){  
            return "byte";  
        }else if(sqlType.equalsIgnoreCase("smallint")){  
            return "short";  
        }else if(sqlType.equalsIgnoreCase("int")){  
            return "int";  
        }else if(sqlType.equalsIgnoreCase("bigint")){  
            return "long";  
        }else if(sqlType.equalsIgnoreCase("float")){  
            return "float";  
        }else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")   
                || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")   
                || sqlType.equalsIgnoreCase("smallmoney")){  
            /*return "double";  */
        	return "String";
        }else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")   
                || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")   
                || sqlType.equalsIgnoreCase("text")){  
            return "String";  
        }else if(sqlType.equalsIgnoreCase("datetime")){  
            /*return "Date";  */
        	return "String";
        }else if(sqlType.equalsIgnoreCase("image")){  
            return "Blod";  
        }  
          
        return null;  
    }  


    /**
     *  将实体类名首字母改为小写
     *
     * @param beanName
     * @return 
     */
    private String processResultMapId( String beanName ) {
        return beanName.substring(0, 1).toLowerCase() + beanName.substring(1);
    }
    private String processType( String type ) {
        if ( type.indexOf(type_char) > -1 ) {
            return "String";
        } else if ( type.indexOf(type_bigint) > -1 ) {
            return "Long";
        } else if ( type.indexOf(type_int) > -1 ) {
            return "Integer";
        } else if ( type.indexOf(type_date) > -1 ) {
            return "String";
        } else if ( type.indexOf(type_text) > -1 ) {
            return "String";
        } else if ( type.indexOf(type_timestamp) > -1 ) {
            return "String";
        } else if ( type.indexOf(type_bit) > -1 ) {
            return "Boolean";
        } else if ( type.indexOf(type_decimal) > -1 ) {
            return "java.math.BigDecimal";
        } else if ( type.indexOf(type_blob) > -1 ) {
            return "byte[]";
        }
        return null;
    }

   
	/** 
     * 出口 
     * TODO 
     * @param args 
     */  
    public static void main(String[] args) {  
          
        new GenEntityMysql();

    }
    public void writeFile(String outputPath,String content){
        try {
            FileWriter fw = new FileWriter(outputPath);
            PrintWriter pw = new PrintWriter(fw);
            pw.println(content);
            pw.flush();
            pw.close();
        }catch (IOException e){
            System.out.println(e.getMessage());
        }

    }
  
}  